package com.chenjun.core.service.oa.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.chenjun.common.Constant;
import com.chenjun.common.bean.Pagination;
import com.chenjun.common.model.DataGridModel;
import com.chenjun.common.model.DataGridSortModel;
import com.chenjun.common.util.DateUtil;
import com.chenjun.core.dao.generator.entity.OaBillAttnDayReport;
import com.chenjun.core.dao.generator.entity.OaBillAttnDetail;
import com.chenjun.core.dao.generator.mapper.OaBillAttnDetailMapper;
import com.chenjun.core.dao.module.OaBillAttnDayReportRelationMapper;
import com.chenjun.core.service.oa.OaBillAttnDetailService;

@Service
@Transactional
@SuppressWarnings("serial")
public class OaBillAttnDetailServiceImpl implements OaBillAttnDetailService {

	@Autowired
	private OaBillAttnDetailMapper oaBillAttnDetailMapper; // 考勤明细
	@Autowired
	private OaBillAttnDayReportRelationMapper dayReportRelationMapper; // 日结信息

	@Override
	public OaBillAttnDetail get(int id) {
		return oaBillAttnDetailMapper.selectByPrimaryKey(id);
	}

	@Override
	public int create(OaBillAttnDetail oaBillAttnDetail) {
		return oaBillAttnDetailMapper.insertSelective(oaBillAttnDetail);
	}

	@Override
	public int delete(int id) {
		if (id <= 0) {
			return 0;
		}
		return oaBillAttnDetailMapper.deleteByPrimaryKey(id);
	}

	@Override
	public int update(OaBillAttnDetail oaBillAttnDetail) {
		return oaBillAttnDetailMapper.updateByPrimaryKeySelective(oaBillAttnDetail);
	}

	@Override
	public int createOrUpdate(OaBillAttnDetail oaBillAttnDetail) {
		int rows = 0;
		if (StringUtils.isBlank(oaBillAttnDetail.getId().toString())) {
			rows = oaBillAttnDetailMapper.insertSelective(oaBillAttnDetail);
		} else {
			rows = oaBillAttnDetailMapper.updateByPrimaryKeySelective(oaBillAttnDetail);
		}
		return rows;
	}

	@Override
	public int editUser(OaBillAttnDetail oaBillAttnDetail) {
		int rows = 0;
		if (StringUtils.isBlank(oaBillAttnDetail.getId().toString())) {
			rows = oaBillAttnDetailMapper.insert(oaBillAttnDetail);
		} else {
			rows = oaBillAttnDetailMapper.updateByPrimaryKeySelective(oaBillAttnDetail);
		}
		return rows;
	}

	@Override
	public int doCountByCondition(DataGridModel param) {
		return 0;
	}

	@Override
	public List<OaBillAttnDetail> doListByCondition(DataGridModel param) {
		return oaBillAttnDetailMapper.doListByCondition(param);
	}

	@Override
	public Pagination doPagination(DataGridModel param) {
		Pagination vo = new Pagination();
		List<OaBillAttnDetail> list = oaBillAttnDetailMapper.doListByCondition(param);
		param.setStart(0);
		param.setRows(0);
		int size = list.size();
		vo.setAaData(list);
		vo.setiTotalRecords(size);
		vo.setsEcho(param.getPage());
		vo.setiTotalDisplayRecords(size);
		return vo;
	}

	@Override
	public List<OaBillAttnDetail> getDistinctByEmplid(DataGridModel param) {
		return oaBillAttnDetailMapper.getDistinctByEmplid(param);
	}
	
	@Override
	public Pagination getAbNormalClock(DataGridModel param) {
		Map<String, Object> params = param.getParams();
		int size = 0;
		List<OaBillAttnDetail> normalClock = new ArrayList<>();
		if(params==null || params.isEmpty()){
		}else if(params.get("startTime") == null || params.get("endTime") == null){
		}else{
			String startTime = params.get("startTime").toString();
			String endTime = params.get("endTime").toString();
			List<String> userIds = (List<String>) params.get("userIds");
			normalClock = getAbNormalClock(startTime, endTime, userIds);
			size = normalClock.size();
		}
		
		Pagination vo = new Pagination();
		vo.setAaData(normalClock);
		vo.setiTotalRecords(size);
		vo.setsEcho(param.getPage());
		vo.setiTotalDisplayRecords(size);
		return vo;
	}

	public List<OaBillAttnDetail> getAbNormalClock(String startTime, String endTime, List<String> userids) {
		if(StringUtils.isBlank(startTime) || StringUtils.isBlank(endTime)){
			return null;
		}
		// 时间处理，取开始到结束日期的所有异常信息
		String start = " 00:00:00";
		String end = " 23:59:59";
		startTime += start;
		endTime += end;
		Date startDate = DateUtil.parseStringToDate(startTime);
		Date endDate = DateUtil.parseStringToDate(endTime);
		Calendar s_calendar = Calendar.getInstance();
		Calendar e_calendar = Calendar.getInstance();
		s_calendar.setTime(startDate);
		e_calendar.setTime(endDate);
		List<OaBillAttnDetail> abnormalClock = new ArrayList<>(); // 存异常打卡数据
		while(s_calendar.getTimeInMillis() <= e_calendar.getTimeInMillis()) { // 遍历时间
			// 遍历这天每个用户的打卡数据，找异常
			String thisDay = DateUtil.dateToStrShort(s_calendar.getTime());
			for (String userid : userids) {
				DataGridModel param = new DataGridModel();
				param.setRows(0);
				param.getParams().put("emplId", userid);
				param.getParams().put("startClockTime", thisDay + start);
				param.getParams().put("endClockTime", thisDay + end);
				param.getSortBy().add(new DataGridSortModel("clock_time", DataGridSortModel.ASC));
				// 取此用户这天的所有打卡数据
				List<OaBillAttnDetail> oaBillAttnDetails = oaBillAttnDetailMapper.doListByCondition(param);
				if (oaBillAttnDetails == null || oaBillAttnDetails.isEmpty()) { // 没有数据
					continue;
				} else if (oaBillAttnDetails.size() == 1) { // 只有一条数据
					abnormalClock.add(oaBillAttnDetails.get(0));
				} else { // 一条数据以上，判断是否为非标准，是否超过8
					if (oaBillAttnDetails.get(0).getManHoursTypeId() == Constant.NONSTANDARD_HOURS_TYPE) { // 非标准工时制
						param = new DataGridModel();
						param.setRows(0);
						param.getParams().put("emplId", userid);
						param.getParams().put("startTime", thisDay);
						param.getParams().put("endTime", thisDay);
						// 取这天的日结数据判断是否超过8小时
						List<OaBillAttnDayReport> dayReports = dayReportRelationMapper.selectByCondition(param);
						if (dayReports != null && !dayReports.isEmpty()) {
							if (dayReports.get(0).getNormalHours() > 8) { // 超过8小时
								for (OaBillAttnDetail oa : oaBillAttnDetails) { // 将所有打卡数据列出
									abnormalClock.add(oa);
								}
							}
						}
					}
				}
			}
			s_calendar.add(Calendar.DAY_OF_MONTH, 1); // 加1天
		}
		return abnormalClock;
	}
	
	@Override
	public float getNormalHours(DataGridModel attnDetailParam){
		float normalHours = 0f;
		// 得到这天所有打卡员工ID
		List<OaBillAttnDetail> userClockRecords = oaBillAttnDetailMapper.doListByCondition(attnDetailParam);
		if (!(userClockRecords == null || userClockRecords.isEmpty())) {
			int size = userClockRecords.size();
			if (size > 1) { // 两次以上打卡数据
				// 取一头一尾
				OaBillAttnDetail startDetail = userClockRecords.get(0);
				OaBillAttnDetail endDetail = userClockRecords.get(size - 1);
				Date firstClockDate = startDetail.getClockTime();// 第一次打卡时间
				Date lastClockDate = endDetail.getClockTime(); // 最后打卡时间
				// 员工第一次打卡时间
				long firstClockTime = DateUtil.strDateToShortTime(DateUtil.dateToShortTime(firstClockDate)).getTime();
				// 员工最后一次打卡时间
				long lastClockTime = DateUtil.strDateToShortTime(DateUtil.dateToShortTime(lastClockDate)).getTime();
				// 与公司设定的上班时间比较
				long companyStartTime = DateUtil.strDateToShortTime("08:30").getTime(); // 公司上班时间
				long companyEndTime = DateUtil.strDateToShortTime("17:30").getTime(); // 公司下班时间
				float companyNormalHours = DateUtil.getDifferenceHour(companyStartTime, companyEndTime).floatValue();
				if(firstClockTime <= companyStartTime){ // 没迟到
					if(lastClockTime >= companyEndTime){ // 没早退
						normalHours = companyNormalHours;
					}else if(lastClockTime > companyStartTime ){ // 早退
						// 最后打卡时间 - 上班时间
						normalHours = DateUtil.getDifferenceHour(companyStartTime, lastClockTime).floatValue();
					}else{
						normalHours = 0f;
					}
				}else{ // 迟到
					if(lastClockTime >= companyEndTime && companyEndTime > firstClockTime){ // 没早退
						// 下班时间 - 最早打卡时间
						normalHours = DateUtil.getDifferenceHour(firstClockTime, companyEndTime).floatValue();
					}else{ // 早退
						// 最后打卡时间 - 最早打卡时间
						normalHours = DateUtil.getDifferenceHour(firstClockTime, lastClockTime).floatValue();
					}
				}
			}
		}
		return normalHours;
	}

}
